package cn.pro.controller;


import cn.pro.api.IProUserService;
import cn.pro.entity.ProUser;
import cn.pro.entity.qo.Query;
import cn.pro.entity.vo.ProUserVo;
import cn.pro.until.FtpUtil;
import cn.pro.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/user")
public class ProUserController {
    @Autowired
    private IProUserService iProUserService;

    @Value("${FTP.ADDRESS}")
    private String host;
    // 端口
    @Value("${FTP.PORT}")
    private int port;
    // ftp用户名
    @Value("${FTP.USERNAME}")
    private String userName;
    // ftp用户密码
    @Value("${FTP.PASSWORD}")
    private String passWord;
    // 文件在服务器端保存的主目录
    @Value("${FTP.BASEPATH}")
    private String basePath;
    // 访问图片时的基础url
    @Value("${IMAGE.BASE.URL}")
    private String baseUrl;

    public static void main(String[] args) {
//        String uId = ObjectUtils.couponCodeTwo("pro");
//        System.out.println(uId);
        List<String> ids = new ArrayList<>();
        ids.add("adasdas");
        ids.add("scsaxsa");
        ids.add("scascsa");
        ids.add("scasc");
        String s = JSON.toJSONString(ids);
        System.out.println(s);
    }

    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public ProData save(@RequestBody ProUserVo proUser){
        proUser.setId(ObjectUtils.couponCodeTwo("pro_user"));
        proUser.setUpdateTime(new Date());
        if (!proUser.getPassWord().equals("")){
            String md5 = EncryptUtil.getInstance().Base64Encode(proUser.getPassWord());
            proUser.setPassWord(md5);
        }
        CheckMsg msg = iProUserService.create(proUser);
        if (msg.isSuccess()){
            return ProData.data("200", VableUtil.SUSSES_STATUS,msg.getMesage());
        }else {
            return ProData.data("201", VableUtil.FAIL_STATUS,msg.getMesage());
        }
    }

    @RequestMapping(value = "/updata",method = RequestMethod.POST)
    public ProData modify(@RequestBody ProUser proUser){
        CheckMsg msg = iProUserService.updateUser(proUser);
        if (msg.isSuccess()){
            return ProData.data("200", VableUtil.SUSSES_STATUS,msg.getMesage());
        }else {
            return ProData.data("201", VableUtil.FAIL_STATUS,msg.getMesage());
        }
    }

    @RequestMapping(value = "selectList",method = RequestMethod.POST)
    public ProData select(@RequestBody ProUser proUser){
        PageData<ProUserVo> userData = iProUserService.selectList(proUser);
        if (!org.springframework.util.ObjectUtils.isEmpty(userData)){
            Object obj = JSONArray.toJSON(userData);
            System.out.println("每页个数："+userData.getPageCount()+"  总数"+userData.getTotalCount());
            return ProData.data("200", VableUtil.SUSSES_STATUS,obj);
        }else {
            return ProData.data("201", VableUtil.FAIL_STATUS,"查询列表为空");
        }
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public ProData deleteUser(@RequestBody Query pro){
        CheckMsg msg = iProUserService.delete(pro.getId());
        if (msg.isSuccess()){
            return ProData.data("200", VableUtil.SUSSES_STATUS,msg.getMesage());
        }else {
            return ProData.data("201", VableUtil.FAIL_STATUS,msg.getMesage());
        }
    }

    @RequestMapping(value = "/select",method = RequestMethod.POST)
    public ProData selectUser(@RequestBody Query pro){
        ProUserVo proUser = iProUserService.selectById(pro.getId());
        if (!org.springframework.util.ObjectUtils.isEmpty(proUser)){
            return ProData.data("200", VableUtil.SUSSES_STATUS, proUser.toString());
        }else {
            return ProData.data("201", VableUtil.FAIL_STATUS,"查询异常");
        }
    }


    /*
    * 登录
    * */
//    @RequestMapping(value = "/login",method = RequestMethod.POST)
//    public ProData selectUser(@RequestBody Query pro){
//
//        ProUser proUser = iProUserService.selectById(pro.getId());
//        if (!org.springframework.util.ObjectUtils.isEmpty(proUser)){
//            return ProData.data("200", VableUtil.SUSSES_STATUS, proUser.toString());
//        }else {
//            return ProData.data("201", VableUtil.FAIL_STATUS,"查询异常");
//        }
//    }

    /*
    * 绑定角色
    * */
    @RequestMapping(value = "/bindRole",method = RequestMethod.POST)
    public ProData bind(@RequestBody Query pro){
        CheckMsg msg = iProUserService.bindRoles(pro.getId(),pro.getIds());
        if (msg.getMesage().contains("成功")){
            return ProData.data("200", VableUtil.SUSSES_STATUS,msg.getMesage());
        }else {
            return ProData.data("201", VableUtil.FAIL_STATUS,msg.getMesage());
        }
    }

    @GetMapping("/upload")
    @ResponseBody
    public String pictureUpload(
            @RequestParam("pic") MultipartFile uploadFile, @RequestParam("id") String userId) {
        try {
            //1、给上传的图片生成新的文件名
            //1.1获取原始文件名
            String oldName = uploadFile.getOriginalFilename();
            //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
            String newName = FtpUtil.genImageName();
            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            //1.3生成文件在服务器端存储的子目录
            String filePath = new DateTime().toString("/yyyy/MM/dd");

            //2、把前端输入信息，包括图片的url保存到数据库
            ProUser user = new ProUser();
            user.setPicture(baseUrl + filePath + "/" + newName);

            ProUserVo proUserVo = iProUserService.selectById(userId);
            proUserVo.setPicture(baseUrl + filePath + "/" + newName);
            iProUserService.create(proUserVo);

            //3、把图片上传到图片服务器
            //3.1获取上传的io流
            InputStream input = uploadFile.getInputStream();

            //3.2调用FtpUtil工具类进行上传
            boolean result = FtpUtil.uploadFile(host, port, userName, passWord, basePath, filePath, newName, input);
            if(result) {
                return "success";
            }else {
                return "false";
            }
        } catch (IOException e) {
            return "false";
        }
    }




}
